package com.mtw.bbs.gateway.config;


import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import java.util.List;

/**
 * 网关白名单配置
 *
 */
@Data
@Component
@ConfigurationProperties(prefix="authorize.enable")
public class AuthorizeUrlsConfig {

    /**
     * 放行的url
     */
    @Value("#{'${authorize.permit:}'.split(',')}")
    private List<String> permitUrls;


    /**
     * 需要登录认证的url
     */
    @Value("#{'${authorize.authentication:}'.split(',')}")
    private List<String> authenticationUrls;


    /**
     * token相关的的url
     */
    @Value("#{'${authorize.token:}'.split(',')}")
    private List<String> tokenUrls;

    /**
     * 需要授权的url
     */
    @Value("#{'${authorize.resource:}'.split(',')}")
    private List<String> resourceUrls;



    private final AntPathMatcher antPathMatcher = new AntPathMatcher();


    /**
     * 当前url是否放行
     */
    public boolean isPermit(String url){
        String urlStr = url.replace("/api/", "/");
        return permitUrls.stream().anyMatch(pattern -> antPathMatcher.match(pattern, urlStr));
    }


    /**
     * 当前url是否需要登录认证
     */
    public boolean isAuthenticationUrl(String url){
        String urlStr = url.replace("/api/", "/");
        return authenticationUrls.stream().anyMatch(pattern -> antPathMatcher.match(pattern, urlStr));
    }


    /**
     * 当前url是否为token相关接口
     */
    public boolean isTokenUrl(String url){
        String urlStr = url.replace("/api/", "/");
        return tokenUrls.stream().anyMatch(pattern -> antPathMatcher.match(pattern, urlStr));
    }


    /**
     * 当前url是否需要授权
     */
    public boolean isResourceUrl(String url){
        String urlStr = url.replace("/api/", "/");
        return resourceUrls.stream().anyMatch(pattern -> antPathMatcher.match(pattern, urlStr));
    }

}
